<template>
  <div class="mout_container">
    <div><h1>vue+element 前端解析excel并表格展示</h1></div>
    <div>
      <!--  excel表格上传  -->
      <el-upload
          class="upload-demo"
          drag
          action="#"
          multiple
          accept=".xlsx,.xls"
          :on-exceed="exceed"
          :limit="1"
          :on-remove="remove"
          :http-request="uploadFile"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">1次只能上传1个Excel（.xlsx或.xls）文件，且不超过500kb</div>
      </el-upload>
    </div>
    <!--  上传的excel表格预览  -->
    <div class="preview-excel">
      <el-table class="listTable_ele" :data="listTable" stripe height="250" style="width:100%">
        <el-table-column prop="name" label="姓名" width="200" align="center"></el-table-column>
        <el-table-column prop="age" label="年龄" width="200" align="center"></el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import XLSX from 'xlsx'

export default {
  mounted () {

  },
  created () {

  },
  methods: {
    //异步上传文件   解析excel
    async uploadFile(params) {
      const _file = params.file;
      const fileReader = new FileReader();
      fileReader.onload = (ev) => {
        try {
          const data = ev.target.result;
          const workbook = XLSX.read(data, {
            type: 'binary'
          });
          for (let sheet in workbook.Sheets) {
            //循环读取每个文件
            const sheetArray = XLSX.utils.sheet_to_json(workbook.Sheets[sheet]);
            //若当前sheet没有数据，则continue
            if(sheetArray.length == 0){
              continue;
            }
            console.log("读取文件");
            console.log(sheetArray);
            for(let item in sheetArray){
              let rowTable = {};
              //这里的rowTable的属性名注意要与上面表格的prop一致
              //sheetArray的属性名与上传的表格的列名一致
              rowTable.name = sheetArray[item].姓名;
              rowTable.age = sheetArray[item].年龄;
              this.listTable.push(rowTable)
            }
          }
        } catch (e) {
          this.$message.warning('文件类型不正确！');
        }
      };
      fileReader.readAsBinaryString(_file);
    },
    //上传1个以上文件时弹窗提示错误
    exceed: function() {
      this.$message.error("1次只能上传1个Excel（.xlsx或.xls）文件");
    },
    //删除文件
    remove() {
      this.listTable = [];
    }
  },
  data() {
    return {
      listTable:[]
    }
  }
}
</script>

<style lang='less' scoped>
</style>
